import os
import sys
import logging
import pygame

try:
    __file__
except NameError as e:
    from whereis import mymain
    rootdir = mymain()
else:
    rootdir = os.path.dirname(os.path.dirname(__file__))

sys.path.insert(0, rootdir)
from lib.bashlog import getlogger
from lib.tracemore import get_exc_plus
from lib.config import Config
from lib.sprite import Sprite
from lib import color
sys.path.pop(0)

logger = logging.getLogger('wordson.checkbox')

cfg = Config()

class CheckBox(Sprite):
    interval = cfg.chkbox_interval
    boxes = []
    def __init__(self):
        super(CheckBox, self).__init__()
        surf = pygame.image.load(os.path.join(rootdir, 'img', 'chkbox.png')).convert_alpha()

        if not self.boxes:    # load images into class(not instance)
            cls = self.__class__
            y = 80
            checking = []
            for idx in range(5):
                x = idx * 80
                subsurf = surf.subsurface((x, y, 80, 80))
                checking.append(subsurf)

            checking.insert(0, surf.subsurface((0, 0, 80, 80)))

            cls.boxes = checking

        self.time = 0
        self.idx = 0

        self.image = self.boxes[0]
        self.rect = self.image.get_rect()
        self.checked = False

    def update(self, time):
        self.time += time
        step = self.time // self.interval
        if step < 1:    # not hit the interval, wait for next update
            return

        self.time = 0
        logger.debug(step)
        if not self.checked:    # erasing
            if self.idx == 0:
                return True

            self.idx = max(self.idx - step, 0)
            self.image = self.boxes[self.idx]
            logger.debug('erasing or stay, %s', self.idx)
            return self.idx == 0

        # drawing
        maxidx = len(self.boxes)-1
        minidx = 2
        idx = max(self.idx+step, minidx)    # it must start to draw(at least be 2)
        idx = min(idx, maxidx)    # should not get out of range

        self.idx = idx
        self.image = self.boxes[idx]
        return (idx == maxidx)

    def handle(self, event):
        if (event.type == pygame.MOUSEBUTTONUP
                and event.button == 1):
            pos = event.pos
            if self.rect.collidepoint(pos):
                self.checked = not self.checked




if __name__ == '__main__':
    getlogger(logger, logging.DEBUG)

    pygame.init()
    pygame.key.set_repeat(cfg.key_repeat_delay, cfg.key_repeat_interval)
    pygame.display.set_caption(cfg.title)

    screen = pygame.display.set_mode(cfg.screen)

    run = True
    clock = pygame.time.Clock()
    chkbox = CheckBox()

    while run:
        for event in pygame.event.get():
            if chkbox.handle(event):
                continue
            if event.type == pygame.QUIT:
                run = False

        inter = clock.tick(cfg.tick)
        chkbox.update(inter)
        screen.fill(color.white)
        chkbox.draw(screen)
        pygame.display.flip()

    pygame.quit()
